// -*- coding: utf-8 -*-
frappe.ui.form.on('Scrap Transaction', {
    refresh: function(frm) {
        // 添加查看余料按钮
        if (frm.doc.scrap_material) {
            frm.add_custom_button(__('查看余料'), function() {
                frappe.open_in_new_tab = true;
                window.open(`/app/scrap-material/${frm.doc.scrap_material}`);
            });
        }
        
        // 添加查看参考文档按钮
        if (frm.doc.reference_document) {
            frm.add_custom_button(__('查看参考文档'), function() {
                frappe.open_in_new_tab = true;
                window.open(`/app/${frm.doc.reference_doctype.toLowerCase().replace(/\s+/g, '-')}/${frm.doc.reference_name}`);
            });
        }
        
        // 添加查看事务历史按钮
        if (frm.doc.scrap_material) {
            frm.add_custom_button(__('查看事务历史'), function() {
                frappe.call({
                    method: 'scrap_management.scrap_management.doctype.scrap_transaction.scrap_transaction.ScrapTransaction.get_transaction_history',
                    args: {
                        scrap_material: frm.doc.scrap_material,
                        limit: 50
                    },
                    callback: function(r) {
                        if (r.message && r.message.length > 0) {
                            // 显示事务历史对话框
                            let dialog = new frappe.ui.Dialog({
                                title: __('余料事务历史'),
                                fields: [
                                    {
                                        fieldtype: 'HTML',
                                        fieldname: 'transaction_history'
                                    }
                                ],
                                primary_action: function() {
                                    dialog.hide();
                                },
                                primary_action_label: __('关闭')
                            });
                            
                            // 构建事务历史表格
                            let html = `
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>${__('事务类型')}</th>
                                            <th>${__('日期')}</th>
                                            <th>${__('时间')}</th>
                                            <th>${__('数量变化')}</th>
                                            <th>${__('变化前数量')}</th>
                                            <th>${__('变化后数量')}</th>
                                            <th>${__('参考文档')}</th>
                                            <th>${__('创建者')}</th>
                                            <th>${__('备注')}</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                            `;
                            
                            r.message.forEach(function(transaction) {
                                html += `
                                    <tr>
                                        <td>${transaction.transaction_type}</td>
                                        <td>${transaction.transaction_date}</td>
                                        <td>${transaction.transaction_time}</td>
                                        <td style="color: ${transaction.quantity_change > 0 ? 'green' : 'red'}">
                                            ${transaction.quantity_change > 0 ? '+' : ''}${transaction.quantity_change}
                                        </td>
                                        <td>${transaction.old_quantity}</td>
                                        <td>${transaction.new_quantity}</td>
                                        <td>${transaction.reference_doctype ? transaction.reference_doctype + ': ' + transaction.reference_name : ''}</td>
                                        <td>${transaction.created_by}</td>
                                        <td>${transaction.remarks || ''}</td>
                                    </tr>
                                `;
                            });
                            
                            html += `
                                    </tbody>
                                </table>
                            `;
                            
                            dialog.fields_dict.transaction_history.$wrapper.html(html);
                            dialog.show();
                        } else {
                            frappe.msgprint(__('没有找到相关的事务历史记录'));
                        }
                    }
                });
            });
        }
        
        // 添加查看每日汇总按钮
        if (frappe.user.has_role(['System Manager', 'Scrap Manager'])) {
            frm.add_custom_button(__('查看每日汇总'), function() {
                frappe.call({
                    method: 'scrap_management.scrap_management.doctype.scrap_transaction.scrap_transaction.ScrapTransaction.get_daily_summary',
                    args: {
                        date: frm.doc.transaction_date,
                        warehouse: frm.doc.warehouse
                    },
                    callback: function(r) {
                        if (r.message) {
                            // 显示每日汇总对话框
                            let dialog = new frappe.ui.Dialog({
                                title: __('每日事务汇总'),
                                fields: [
                                    {
                                        fieldtype: 'HTML',
                                        fieldname: 'daily_summary'
                                    }
                                ],
                                primary_action: function() {
                                    dialog.hide();
                                },
                                primary_action_label: __('关闭')
                            });
                            
                            // 构建每日汇总表格
                            let summary = r.message;
                            let html = `
                                <div class="row">
                                    <div class="col-md-6">
                                        <h5>${__('基本信息')}</h5>
                                        <table class="table table-bordered">
                                            <tr>
                                                <th>${__('日期')}</th>
                                                <td>${summary.date}</td>
                                            </tr>
                                            <tr>
                                                <th>${__('总入库')}</th>
                                                <td style="color: green">${summary.total_in}</td>
                                            </tr>
                                            <tr>
                                                <th>${__('总出库')}</th>
                                                <td style="color: red">${summary.total_out}</td>
                                            </tr>
                                            <tr>
                                                <th>${__('净变化')}</th>
                                                <td style="color: ${summary.net_change >= 0 ? 'green' : 'red'}">${summary.net_change}</td>
                                            </tr>
                                            <tr>
                                                <th>${__('事务总数')}</th>
                                                <td>${summary.total_count}</td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-md-6">
                                        <h5>${__('按类型汇总')}</h5>
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>${__('事务类型')}</th>
                                                    <th>${__('入库')}</th>
                                                    <th>${__('出库')}</th>
                                                    <th>${__('数量')}</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                            `;
                            
                            summary.summary.forEach(function(item) {
                                html += `
                                    <tr>
                                        <td>${item.transaction_type}</td>
                                        <td style="color: green">${item.total_in}</td>
                                        <td style="color: red">${item.total_out}</td>
                                        <td>${item.count}</td>
                                    </tr>
                                `;
                            });
                            
                            html += `
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            `;
                            
                            dialog.fields_dict.daily_summary.$wrapper.html(html);
                            dialog.show();
                        }
                    }
                });
            });
        }
    },
    
    scrap_material: function(frm) {
        // 余料变更时，获取余料详细信息
        if (frm.doc.scrap_material) {
            frappe.call({
                method: 'scrap_management.utils.get_scrap_material_details',
                args: {
                    scrap_material_id: frm.doc.scrap_material
                },
                callback: function(r) {
                    if (r.message) {
                        let material = r.message;
                        frm.set_value('material_type', material.material_type);
                        frm.set_value('material_name', material.material_name);
                        frm.set_value('color', material.color);
                        frm.set_value('length', material.length);
                        frm.set_value('width', material.width);
                        frm.set_value('thickness', material.thickness);
                        frm.set_value('unit', material.unit);
                        frm.set_value('unit_price', material.unit_price);
                        frm.set_value('warehouse', material.warehouse);
                        frm.set_value('location', material.location);
                    }
                }
            });
        }
    },
    
    transaction_type: function(frm) {
        // 事务类型变更时，设置默认数量变化方向
        if (frm.doc.transaction_type) {
            if (frm.doc.transaction_type === '入库') {
                frm.set_value('quantity_change', 1);
            } else if (frm.doc.transaction_type === '出库' || frm.doc.transaction_type === '领料' || frm.doc.transaction_type === '消耗') {
                frm.set_value('quantity_change', -1);
            } else if (frm.doc.transaction_type === '调整') {
                frm.set_value('quantity_change', 0);
            }
        }
    },
    
    quantity_change: function(frm) {
        // 数量变化变更时，计算新数量
        if (frm.doc.old_quantity !== undefined && frm.doc.old_quantity !== null) {
            let new_quantity = frm.doc.old_quantity + frm.doc.quantity_change;
            frm.set_value('new_quantity', new_quantity);
        }
    },
    
    old_quantity: function(frm) {
        // 旧数量变更时，计算新数量
        if (frm.doc.quantity_change !== undefined && frm.doc.quantity_change !== null) {
            let new_quantity = frm.doc.old_quantity + frm.doc.quantity_change;
            frm.set_value('new_quantity', new_quantity);
        }
    },
    
    validate: function(frm) {
        // 验证数量变化
        if (frm.doc.quantity_change === 0) {
            frappe.msgprint(__('数量变化不能为零'));
            frappe.validated = false;
            return;
        }
        
        // 验证事务类型和数量变化方向是否一致
        if (frm.doc.transaction_type === '入库' && frm.doc.quantity_change <= 0) {
            frappe.msgprint(__('入库事务的数量变化必须为正数'));
            frappe.validated = false;
            return;
        } else if ((frm.doc.transaction_type === '出库' || frm.doc.transaction_type === '领料' || frm.doc.transaction_type === '消耗') && frm.doc.quantity_change >= 0) {
            frappe.msgprint(__('{0}事务的数量变化必须为负数', [frm.doc.transaction_type]));
            frappe.validated = false;
            return;
        }
        
        // 验证数量变化是否一致
        let expected_new_quantity = frm.doc.old_quantity + frm.doc.quantity_change;
        if (Math.abs(frm.doc.new_quantity - expected_new_quantity) > 0.0001) {
            frappe.msgprint(__('数量变化不一致，期望新数量为 {0}，实际为 {1}', [expected_new_quantity, frm.doc.new_quantity]));
            frappe.validated = false;
            return;
        }
    }
});